package com.itemp.wifidirectsend;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;

/**
 * WiFi Direct  Server
 * 服务端接收文件
 * 2025-4-16 Jackly
 */
public class FileReceiverActivity extends BaseActivity implements DirectActionListener {
    private static final String TAG = "WifiDirectReceiver";
    private WifiManagerUtils wifiManagerUtils;
    private WifiP2pManager mWifiP2pManager;
    private WifiP2pManager.Channel wifiP2pChannel;
    private DirectBroadcastReceiver broadcastReceiver;
    private ProgressDialog loadingDialog;
    private WifiServerService wifiServerService;
    private TextView tvLog,wifiMacTv,p2pMacTv;
    private Button btnCreateGroup, btnRemoveGroup, btnStartReceive;
    private ImageView wlan1Image;
    private String wlan0Address,wlan1Address;

    private String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_receiver);
        if(!Settings.canDrawOverlays(this)){
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
        }
        requestPermission(permissions);
        initDevice();
    }

    @SuppressLint("MissingPermission")
    private void createGroup() {
        Log.d(TAG,"createGroup");
        showLoadingDialog("Create group...");
        removeGroupIfNeed();
        mWifiP2pManager.createGroup(wifiP2pChannel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "createGroup onSuccess");
                dismissLoadingDialog();
                Log.d(TAG, "onSuccess");
            }

            @Override
            public void onFailure(int reason) {
                Log.e(TAG, "createGroup onFailure: " + reason);
                dismissLoadingDialog();
                Log.d(TAG, "onFailure");
            }
        });
    }

    @SuppressLint("MissingPermission")
    private void removeGroupIfNeed() {
        mWifiP2pManager.requestGroupInfo(wifiP2pChannel, wifiP2pGroup -> {
            mWifiP2pManager.removeGroup(wifiP2pChannel, new WifiP2pManager.ActionListener() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onFailure(int i) {

                }
            });
        });
    }

    @SuppressLint("WrongViewCast")
    private void initDevice() {
        mWifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        wifiP2pChannel = mWifiP2pManager.initialize(this, getMainLooper(), this);
        broadcastReceiver = new DirectBroadcastReceiver(mWifiP2pManager, wifiP2pChannel, this);
        registerReceiver(broadcastReceiver, DirectBroadcastReceiver.getIntentFilter());
        tvLog = findViewById(R.id.log_tv);
        btnCreateGroup = findViewById(R.id.btn_create_group);
        btnCreateGroup.setOnClickListener(view -> createGroup());
        wlan1Image = findViewById(R.id.p2p_iv);
        wifiManagerUtils = new WifiManagerUtils(this);
        wifiManagerUtils.openWifiEnabled();

        startWifiServerService();
        createGroup();
        btnCreateGroup.postDelayed(() -> {
            createGroup();
        },200);


        wlan1Address =getWlan1Address();
        Bitmap bitmap1 = Utils.createQRCodeBitmap(wlan1Address, 245, 245, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
        wlan1Image.setImageBitmap(bitmap1);

        p2pMacTv = findViewById(R.id.p2p_mac_tv);
        p2pMacTv.setText("P2P MAC:" + wlan1Address);
    }

    public String getWlan1Address(){
        return getString("sys/class/net/p2p0/address");
    }

    private String getString(String path) {
        String prop = "";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(path));
            prop = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }
    @Override
    protected void onStart() {
        super.onStart();
        openWifiEnabled();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void startWifiServerService() {
        Log.d(TAG,"startWifiServerService");
        Intent intent = new Intent(this, WifiServerService.class);
        startService(intent);
    }
    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WifiServerService.MyBinder myBinder = (WifiServerService.MyBinder) service;
            wifiServerService = myBinder.getWifiServerService();
            wifiServerService.setOnProgressChangListener(progressChangListener);
        }
    };

    private OnProgressChangListener progressChangListener = new OnProgressChangListener() {
        @Override
        public void onProgressChanged(final FileTransfer fileTransfer, final int progress) {
            runOnUiThread(() -> {
                showProgressDialog("File name: " + new File(fileTransfer.getFilePath()).getName());
                loadingDialog.setProgress(progress);
            });
        }

        @Override
        public void onTransferFinished(final File file) {
            runOnUiThread(() -> {
                if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.cancel();
                if (file != null && file.exists()) {
                    tvLog.setText("onTransferFinished, file:" + file.getPath());
//                    openFile(file.getPath());
                }
            });
        }
    };

    private void showProgressDialog(String message) {
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        loadingDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        loadingDialog.setCancelable(true);
        loadingDialog.setMessage(message);
        loadingDialog.setMax(100);
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
    }


    @Override
    public void wifiP2pEnabled(boolean enabled) {
        Log.d(TAG, "wifiP2pEnabled = " + enabled);
    }

    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        String log = "onConnectionInfoAvailable " + "\n"
                + "isGroupOwner: " + wifiP2pInfo.isGroupOwner + "\n"
                + "groupFormed: " + wifiP2pInfo.groupFormed + "\n"
                + "groupOwnerAddress: " + wifiP2pInfo.groupOwnerAddress;
        tvLog.setText(log);
        Log.d(TAG, log);
    }

    @Override
    public void onDisconnection() {
        Log.d(TAG, "onDisconnection");
    }

    @Override
    public void onSelfDeviceAvailable(WifiP2pDevice wifiP2pDevice) {
        Log.d(TAG, "onSelfDeviceAvailable " + wifiP2pDevice.toString());
    }

    @Override
    public void onPeersAvailable(Collection<WifiP2pDevice> wifiP2pDeviceList) {
        Log.d(TAG, "onPeersAvailable, size:" + wifiP2pDeviceList.size());
        for (WifiP2pDevice wifiP2pDevice : wifiP2pDeviceList) {
            Log.d(TAG, wifiP2pDevice.toString());
        }
    }

    @Override
    public void onChannelDisconnected() {
        Log.d(TAG, "onChannelDisconnected");
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 0 && resultCode == RESULT_OK) {
//            String result = data.getStringExtra("SCAN_RESULT");
//            Log.d(TAG, "result = " + result);
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
        removeGroupIfNeed();
        stopService(new Intent(this,WifiServerService.class));
    }
}